<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户列表</span>
      </div>
      <!-- 搜索区域 -->
      <el-input placeholder="请输入内容" v-model="queryInfo.searchContent" clearable
                @clear="getUserList">
        <el-select v-model="queryInfo.select" slot="prepend" placeholder="请选择">
          <el-option label="职工工号" value="workNumber"></el-option>
          <el-option label="职工姓名" value="employeeName"></el-option>
          <el-option label="工作部门" value="department"></el-option>
        </el-select>
        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
      </el-input>
      <el-button class="addButton" type="primary" @click="showAddDialog">新增</el-button>
      <el-button type="primary" @click="excelDialogVisible=true">Excel导入用户列表</el-button>
      <!-- 导出Excel -->
      <el-button :loading="downloadLoading"
                 style="margin-bottom:20px"
                 type="primary"
                 icon="el-icon-document"
                 @click="handleDownload"
      >导出为Excel</el-button>
      <!-- 用户列表区域-->
      <el-table :data="userList" border stripe
                :header-cell-style="{'text-align':'center'}"
                :cell-style="{'text-align':'center'}">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="workNumber" label="职工工号"></el-table-column>
        <el-table-column prop="name" label="职工姓名"></el-table-column>
        <el-table-column prop="department" label="职工部门" ></el-table-column>
        <el-table-column prop="phone" label="联系方式"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="age" label="年龄"></el-table-column>
        <el-table-column prop="role" label="角色"></el-table-column>
        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <!--编辑用户按钮-->
            <el-tooltip class="item" effect="dark" content="编辑用户" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.userId)"></el-button>
            </el-tooltip>
            <!--重置密码按钮-->
            <el-tooltip class="item" effect="dark" content="重置密码" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-lock" size="mini" @click="showResetPasswordDialog(scope.row.userId)"></el-button>
            </el-tooltip>
            <!--删除按钮-->
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="showDeleteDialog(scope.row.userId)"></el-button>
            </el-tooltip>
            <!--分配权限-->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" circle @click="showSetRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :total="total"
        :current-page="queryInfo.nowpage"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
      >
      </el-pagination>
    </el-card>
    <!-- 增加用户表单的对话框 -->
    <el-dialog title="用户表单" :visible.sync="addDialogVisible" width="40%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="职工工号" prop="username">
          <el-input class="form-input" v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="职工姓名" prop="name">
          <el-input class="form-input" v-model="userForm.name"></el-input>
        </el-form-item>
        <el-form-item label="职工部门" prop="department">
          <el-input class="form-input" v-model="userForm.department"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input class="form-input" v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input class="form-input" type="age" v-model.number="userForm.age" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="formSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="40%" @close="editDialogClosed">
      <!-- 内容主体 -->
      <el-form
        :model="editUserForm"
        ref="editUserFormRef"
        :rules="editUserFormRules"
        label-width="100px"
      >
        <el-form-item label="职工工号" prop="username">
          <el-input class="form-input" v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="职工姓名" prop="name">
          <el-input class="form-input" v-model="editUserForm.name"></el-input>
        </el-form-item>
        <el-form-item label="职工部门" prop="department">
          <el-input class="form-input" v-model="editUserForm.department"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input class="form-input" v-model="editUserForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input class="form-input" type="age" v-model.number="editUserForm.age" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 重置用户密码的对话框 -->
    <el-dialog title="重置用户密码提示" :visible.sync="resetPasswordDialogVisible" width="30%" >
      <!-- 内容主体区域 -->
      <span>确定将用户密码重置为职工工号吗?</span>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
            <el-button @click="resetPasswordDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="resetPassword">确 定</el-button>
          </span>
    </el-dialog>
    <!-- 删除用户的对话框 -->
    <el-dialog title="删除用户提示" :visible.sync="deleteDialogVisible" width="30%" >
      <!-- 内容主体区域 -->
      <span>确定删除该用户吗?</span>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
      <div>
        <p>当前用户账号：{{userInfo.workNumber}}</p>
        <p>当前角色：{{userInfo.role}}</p>
        <p>
          分配角色：
          <el-select style="width: 200px"
            v-model="selectRoleId"
            filterable
            allow-create
            default-first-option
            placeholder="请选择角色"
          >
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 导入Excel时，弹出对话框 -->
    <el-dialog title="导入用户" :visible.sync="excelDialogVisible" width="80%" @close="excelDialogClosed">
      <!-- 内容主体区域 -->
      <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
      <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
        <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
      </el-table>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
          <el-button @click="excelDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="importUsers">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getUsers,
  addUser,
  // eslint-disable-next-line no-unused-vars
  updateUser,
  deleteUser,
  getUser,
  editUser,
  resetUser
} from '@/api/user'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
const qs=require('querystring')
export default {
  components: { UploadExcelComponent },
  data: function () {
    // 自定义验证手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      // 返回一个错误提示
      callback(new Error('请输入合法的手机号码'))
    }
    return {
      // 用户列表
      userList: [],
      // 总数
      total: 0,
      // 查询列表参数信息
      queryInfo: {
        // 当前页数
        nowPage: 1,
        // 当前每页显示多少条数据
        pageSize: 10,
        // 选择种类
        select: '',
        // 搜索内容
        searchContent: ''
      },
      // 控制新增用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 控制重置用户密码对话框的显示与隐藏
      resetPasswordDialogVisible: false,
      // 控制删除用户对话框的显示与隐藏
      deleteDialogVisible: false,
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 控制excel导入的显示与隐藏
      excelDialogVisible: false,
      // 操作的表格对象id
      idInfo: {
        userId: 0
      },
      // 新增用户表单内容
      userForm: {
        username: '', // 用户工号
        name: '', // 用户姓名
        department: '', // 用户部门
        phone: '', // 用户电话号码
        sex: '', // 用户性别
        age: '', // 用户年龄
        auth: ''// 用户角色
      },
      // 新增用户表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入职工工号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请填写职工姓名', trigger: 'blur' }
        ],
        department: [
          { required: true, message: '请输入职工部门', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入职工电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        age: [
          { required: true, message: '请填写年龄', trigger: 'blur' },
          { type: 'number', message: '年龄必须为数字', trigger: 'blur' }
        ]
      },
      // 编辑用户的表单
      editUserForm: {},
      // 编辑用户表单验证
      editUserFormRules: {
        name: [
          { required: true, message: '请填写职工姓名', trigger: 'blur' }
        ],
        department: [
          { required: true, message: '请输入职工部门', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入职工电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请填写年龄', trigger: 'blur' },
          { type: 'number', message: '年龄必须为数字', trigger: 'blur' }
        ]
      },
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色ID值
      selectRoleId: '',
      // excel相关
      tableData: [],
      tableHeader: [],
      // 导出Excel
      excelList: [],
      downloadLoading: false,
      autoWidth: true,
      bookType: 'xlsx'
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    /**
       * 获取全部用户列表
     */
    async getUserList () {
      const res = await getUsers(this.queryInfo)
      //console.log(res)
      if (res.status !== 200) {
        if(res.status===403){
          return this.$message.error('您没有获取用户列表的权限!')
        }
        return this.$message.error('获取用户列表失败!')
      }
      this.userList = []
      for (var i = 1; i < res.data.length; i++) {
        this.userList.push(res.data[i])
      }
      this.total = res.data[0].number
    },

    /**
       * 监听分页尺寸改变
       * @param newSize:新的分页尺寸
       */
    handleSizeChange (newSize) {
      this.queryInfo.Pagesize = newSize
      this.getUserList()
    },

    /**
       * 监听当前页码变化
       * @param nowPage:当前页码
       */
    handleCurrentChange (nowPage) {
      this.queryInfo.nowPage = nowPage
      this.getUserList()
    },

    /**
       * 展示添加用户的对话框
       */
    showAddDialog () {
      this.addDialogVisible = true
    },

    /**
       * 提交用户表单
       * @param formName:用户表单引用名
       */
    formSubmit () {
      // console.log(this.userForm)
      this.$refs.userFormRef.validate(async (valid) => {
        if (valid) {
          this.addUser()
        } else {
          this.$message.error('用户信息不合法!')
          return false
        }
      })
    },

    /**
       * 向后台发起添加用户请求
       */
    async addUser () {
      const res = await addUser(this.userForm)
      console.log(res)
      // eslint-disable-next-line eqeqeq
      if (res.status != 200) {
        if(res.status === 403) {
          return this.$message.error('您没有添加用户的权限!')
        }
        this.$message.error('网络开小差了,请稍后再试!')
      } else {
        // eslint-disable-next-line eqeqeq
        if (res.data.status != 'success') {
          this.$message.error('该用户名已被注册!')
          return false
        }
        this.$message.success('添加用户成功')
        this.addDialogVisible = false
        this.getUserList()
      }
    },

    /**
       * 关闭添加用户对话框之后的重置
       */
    addDialogClosed () {
      this.$refs.userFormRef.resetFields()
    },

    /**
       * 展示修改用户的对话框
       */
    async showEditDialog (id) {
      this.idInfo.userId = id
      const res = await getUser(this.idInfo)
      if (res.status !== 200) {
        if(res.status === 403) {
          return this.$message.error('您没有编辑用户的权限!')
        }
        return this.$message.error('查询用户信息失败！')
      }
      this.editUserForm = res.data
      this.editDialogVisible = true
    },

    /**
       * 编辑用户
       */
    editUser () {
      //console.log(this.editUserForm.userId)
      // 提交请求前，表单预验证
      this.$refs.editUserFormRef.validate(async valid => {
        // 表单预校验失败
        if (!valid) {
          this.$message.error('用户信息不合法!')
          return false
        }
        const res = await editUser({
          userId: this.editUserForm.userId,
          username: this.editUserForm.username,
          password: this.editUserForm.password,
          auth: this.editUserForm.auth,
          name: this.editUserForm.name,
          department: this.editUserForm.department,
          phone: this.editUserForm.phone,
          age: this.editUserForm.age,
          sex: this.editUserForm.sex
        })

        console.log(res)
        if (res.status !== 200) {
          this.$message.error('网络开小差了，请稍后再试！')
          return false
        }
        // 隐藏添加用户对话框
        this.editDialogVisible = false
        this.$message.success('更新用户信息成功！')
        this.getUserList()
      })
    },

    /**
       * 关闭编辑用户对话框之后的重置
       */
    editDialogClosed () {
      this.$refs.editUserFormRef.resetFields()
    },

    /**
       * 展示重置用户密码的对话框
       */
    showResetPasswordDialog (id) {
      this.resetPasswordDialogVisible = true
      this.idInfo.userId = id
    },

    /**
       * 重置用户密码
       */
    async resetPassword () {
      const res = await resetUser(this.idInfo)
      if (res.status !== 200) {
        if(res.status === 403) {
          return this.$message.error('您没有重置用户密码的权限!')
        }
        return this.$message.error('网络开小差了，请稍后重试')
      } else {
        this.$message.success('重置用户密码成功')
      }
      this.resetPasswordDialogVisible = false
    },

    /**
       * 展示删除用户的对话框
       */
    showDeleteDialog (id) {
      this.idInfo.userId = id
      this.deleteDialogVisible = true
    },

    /**
     * 删除用户的方法
     */
    async deleteUser () {
      const res = await deleteUser(this.idInfo)
      if (res.status !== 200) {
        if(res.status === 403) {
          return this.$message.error('您没有删除用户的权限!')
        }
        return this.$message.error('删除失败!')
      } else {
        if(res.data.status===200){
          this.$message.success('删除成功')
        } else{
          this.$message.error(res.data.msg)
        }
      }
      this.getUserList()
      this.deleteDialogVisible = false
    },

    /**
     * 展示分配角色对话框
     */
    async showSetRole (role) {
      //console.log(role.roleId)
      this.userInfo = role
      // 展示对话框之前，获取所有角色列表
      let res = await this.$http.get('roles')
      if (res.status !== 200) {
        if(res.status === 403) {
          return this.$message.error('您没有分配角色的权限!')
        }
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },

    /**
     * 分配角色
     */
    async saveRoleInfo () {
      console.log(this.selectRoleId)
      if (this.selectRoleId==='') {
        return this.$message.error('请选择要分配的角色')
      }
      let params={
        roleId: this.selectRoleId
      }
      let res = await this.$http.put(`user/${this.userInfo.userId}/role`, qs.stringify(params),{
        headers: {'Content-Type' : 'application/x-www-form-urlencoded'}
      })
      if (res.status !== 200) {
        if(res.status === 403) {
          return this.$message.error('您没有分配角色的权限!')
        }
        return this.$message.error('更新用户角色失败！')
      }
      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    },

    /**
     * 分配角色对话框关闭事件
     */
    setRoleDialogClosed () {
      this.selectRoleId = ''
      this.userInfo = {}
    },

    /**
     * 导入Excel前的检查
     * @param file
     * @returns {boolean}
     */
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },

    /**
     * 上传成功后的处理
     * @param results
     * @param header
     */
    async handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
    },

    /**
     * 关闭导入excel用户对话框之后的重置
     */
    excelDialogClosed () {
      this.tableData = []
      this.tableHeader = []
    },

    /**
     * 上传excel表的用户信息
     */
    async importUsers(){
      let params={
        excelData: this.tableData
      }
      let res=await this.$http.post('import-users',params,{
        headers: {
          'Content-Type': 'application/json'
        }})
      if(res.status !== 200){
        if(res.status === 403) {
          return this.$message.error('您没有导入用户的权限!')
        }
        return this.$message.error('有部分用户已存在！')
      }
      if(res.data==false){
        return this.$message.error('有部分用户已存在！')
      }
      this.excelDialogVisible=false
      this.getUserList()
    },

    /**
     * 获取全部用户,用于excel导出
     */
    async getAllUsers(){
      let res=await this.$http.get('all-users')
      this.excelList = res.data
    },

    /**
     * 导出Excel
     */
    async handleDownload() {
      this.downloadLoading = true
      let res=await this.getAllUsers()  //获取全部用户
      import('@/utils/Export2Excel').then(excel => {
        const tHeader = ['职工工号', '职工姓名','职工部门','联系方式','性别','年龄']
        const filterVal = ['username', 'name','department','phone','sex','age']
        const data = this.formatJson(filterVal, this.excelList)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
  }
}
</script>
<style lang="less" scoped>
  .el-input {
    width: 500px;
  }
  .el-select {
    width: 110px;
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .el-table {
    margin-top: 15px;
    font-size: 12px;
  }
  .el-pagination {
    margin-top: 15px;
  }
  .addButton {
    margin-left: 20px;
  }
  .form-input {
    width: 80%;
  }
  .upload-demo {
    width: 70%;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .el-icon-upload {
    width: 40%;
  }
  .el-upload__text {
    margin: 0 auto;
    width: 60%;
  }
  .el-upload__tip {
    width: 60%;
  }
</style>
